package CustomUI;

import java.util.ArrayList;
import java.util.Collections;

import DTO.DrawingDTO;
import android.R.bool;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class ydLayerHolder extends LinearLayout {

	ArrayList<ydLayerCell> layerCells = new ArrayList<ydLayerCell>();

	public ydLayerHolder(Context context, AttributeSet attrs) {
		super(context, attrs);
		//setBackgroundColor(Color.CYAN);
	}

	public void addLayerCell(ydLayerCell lV) {
		layerCells.add(lV);

		addView(lV);

	}

	public void addLayerCell(ydLayerCell im2, int zindex, DrawingDTO drawing) {
		boolean doesExist=false;
		for(int i=0; i<drawing.getLayer().size(); i++){
			if(drawing.getLayer().get(i).getZindex()==zindex){
				if(i>layerCells.size()){
					i=layerCells.size();
				}
				layerCells.add(i, im2);
				doesExist=true;
				break;
			}
		}
		
		if(!doesExist){
			layerCells.add(im2);
		}
		
		this.removeAllViews();
		ydLayerCell l;
		for (int i = 0; i < layerCells.size(); i++) {
			l = layerCells.get(i);
			addView(l);
		}
		
		invalidate();
		
	}

	public void moveUp(int id) {
		ydLayerCell l;
		Log.d("ydLayerHolder:MoveUp", "layerCells.size()=" + layerCells.size()+ "");
		for (int i = 0; i < layerCells.size(); i++) {
			l = layerCells.get(i);
			if (l.getlID() == id) {
				Log.d("ydLayerHolder:MoveUp", "i=" + i+ "");
				if (i != 0){
					//Collections.swap(layerCells, i, i - 1);
					layerCells.remove(i);
					layerCells.add(i-1, l);
					break;
				}
				else
					return;
			}
		}
		this.removeAllViews();

		for (int i = 0; i < layerCells.size(); i++) {
			l = layerCells.get(i);
			addView(l);
		}
		
		invalidate();
	}

	public void moveDown(int id) {
		ydLayerCell l;
		Log.d("ydLayerHolder:MoveDown", "layerCells.size()=" + layerCells.size()+ "");
		for (int i = 0; i < layerCells.size(); i++) {
			l = layerCells.get(i);
			if (l.getlID() == id) {
				Log.d("ydLayerHolder:MoveDown", "i=" + i+ "");
				if (i != layerCells.size() - 1){
					//Collections.swap(layerCells, i, i + 1);
					layerCells.remove(i);
					layerCells.add(i+1, l);
					break;
				}
				else
					return;
			}
		}
		this.removeAllViews();

		for (int i = 0; i < layerCells.size(); i++) {
			l = layerCells.get(i);
			addView(l);
		}

		invalidate();
		
	}

	public void removeLayerCell(ydLayerCell im) {
		layerCells.remove(im);
		this.removeView(im);
		
	}

}
